Overview:
- One or more documents present in a MongoDB collection can be modified using the following methods of PyMongo:
- collection.update_one()
- collection.update_many()
- collection.replace_one()
- In the filter condition for the update methods, a specific operator can be provided based on the type of the field and the kind of operation applied on the field.
Updating multiple MongoDB documents:
- The Python example program below, uses collection.update_many()method to update any number of documents in a MongoDB collection, that matches a specified filter criteria.
- In this example, in all the documents of a MongoDB collection named orders, where the value for the field avenue matches the string “NASDAQGS”, those values are modified to “NYSE”.
Example:
# import MongoClient from pymongo # Create a MongoDB client # Get a collection instance # Update the venue in the order documents # Print the updated document count |
Output:
Number of documents updated on the MongoDB collection: 3 |
Replacing the whole Document of a MongoDB collection:
- A specific document in a collection can be replaceds with another document by specifying a filter condition.
Example:
# import MongoClient from pymongo from pymongo import MongoClient
# Create a MongoDB client mongoDBConnection = MongoClient('localhost', 27017)
# Get a collection instance collection = mongoDBConnection.sample.exhibits
# Print the collection before replacing a document print("Contents of a MongoDB document collection before replacing an erroneous document:") for doc in collection.find(): print(doc)
# Replace a document who has several corrections at field level and value level updateResult = collection.replace_one({"title": "Encyclopedia of everything under the universe"}, { "title": "Encyclopedia of everything under the universe", "author":"Authors", "authorcount":25000, "type": "DVD", "isbn": "xxx-x-xx-xxxxxx-m" } )
# Print the collection after replacing an erroneous document print("Contents of a MongoDB document collection after replacing an erroneous document:") for doc in collection.find(): print(doc) |
Output:
Contents of a MongoDB document collection before replacing an erroneous document: {'_id': ObjectId('5aba7fe074d9af6fff2f2219'), 'title': 'Encyclopedia of everything under the universe', 'author': 'Author Name', 'type': 'Book', 'isbn': 'xxx-x-xx-xxxxxx-a'} {'_id': ObjectId('5aba802174d9af6fff2f221a'), 'title': 'Unwritten book', 'author': 'Author Name', 'type': 'Book', 'isbn': 'xxx-x-xx-xxxxxx-b'} Contents of a MongoDB document collection after replacing an erroneous document: {'_id': ObjectId('5aba7fe074d9af6fff2f2219'), 'title': 'Encyclopedia of everything under the universe', 'author': 'Authors', 'authorcount': 25000, 'type': 'DVD', 'isbn': 'xxx-x-xx-xxxxxx-m'} {'_id': ObjectId('5aba802174d9af6fff2f221a'), 'title': 'Unwritten book', 'author': 'Author Name', 'type': 'Book', 'isbn': 'xxx-x-xx-xxxxxx-b'} |